<template>
  <div class="salary-container">
    <div class="header">
      <h2>工资发放管理</h2> 
    </div>
    <!-- 搜索区域-->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="岗位名称">
          <el-input
            v-model="searchForm.positionName"
            placeholder="请输入岗位名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="学生姓名">
          <el-input
            v-model="searchForm.studentName"
            placeholder="请输入学生姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="待审核" :value="0" />
            <el-option label="已发放" :value="1" />
            <el-option label="未发放" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-section">
      <el-table
        :data="salaryList"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="positionName" label="岗位名称" min-width="150" />
        <el-table-column prop="studentName" label="学生姓名" min-width="120" />
        <el-table-column prop="hourlyRate" label="薪资(元/小时)" min-width="120">
          <template #default="scope">
            {{ scope.row.hourlyRate }}
          </template>
        </el-table-column>
        <el-table-column prop="totalHour" label="总工时(小时)" min-width="100">
          <template #default="scope">
            {{ scope.row.totalHour }}
          </template>
        </el-table-column>
        <el-table-column prop="totalSalary" label="总工资(元)" min-width="120">
          <template #default="scope">
            {{ scope.row.totalSalary }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="scope">
            <el-tag
              :type="getStatusType(scope.row.status)"
              size="small"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="180" fixed="right">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 2"
              type="primary"
              size="small"
              @click="handleReSubmit(scope.row)"
            >
              发放
            </el-button>
            <el-button
              v-if="scope.row.status === 2"
              type="warning"
              size="small"
              @click="handleEdit(scope.row)"
            >
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          background
          layout="prev, pager, next, jumper, ->, total"
          :total="pagination.total"
          :page-size="pagination.pageSize"
          :current-page="pagination.currentPage"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="工资详情"
      width="600px"
    >
      <div v-if="currentDetail" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="岗位名称">
            {{ currentDetail.positionName }}
          </el-descriptions-item>
          <el-descriptions-item label="学生姓名">
            {{ currentDetail.studentName }}
          </el-descriptions-item>
          <el-descriptions-item label="薪资标准">
            ¥{{ currentDetail.hourlyRate }}/小时
          </el-descriptions-item>
          <el-descriptions-item label="总工时">
            {{ currentDetail.totalHour }}小时
          </el-descriptions-item>
          <el-descriptions-item label="总工资">
            <span class="salary-amount">¥{{ currentDetail.totalSalary }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentDetail.status)">
              {{ getStatusText(currentDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请时间" :span="2">
            {{ currentDetail.applyTime }}
          </el-descriptions-item>
          <el-descriptions-item label="审核时间" :span="2" v-if="currentDetail.auditTime">
            {{ currentDetail.auditTime }}
          </el-descriptions-item>
          <el-descriptions-item label="发放时间" :span="2" v-if="currentDetail.payTime">
            {{ currentDetail.payTime }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2" v-if="currentDetail.remark">
            {{ currentDetail.remark }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 修改工资对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改工资信息"
      width="500px"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="120px"
      >
        <el-form-item label="岗位名称">
          <el-input v-model="editForm.positionName" disabled />
        </el-form-item>
        <el-form-item label="学生姓名">
          <el-input v-model="editForm.studentName" disabled />
        </el-form-item>
        <el-form-item label="薪资标准">
          <el-input v-model="editForm.hourlyRate" disabled>
            <template #append>元/小时</template>
          </el-input>
        </el-form-item>
        <el-form-item label="总工时" prop="totalHour">
          <el-input-number
            v-model="editForm.totalHour"
            :min="0"
            :precision="2"
            :step="1"
            style="width: 100%"
          >
            <template #append>小时</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="总工资" prop="totalSalary">
          <el-input-number
            v-model="editForm.totalSalary"
            :min="0"
            :precision="2"
            :step="1"
            style="width: 100%"
          >
            <template #prepend>¥</template>
          </el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveEdit" :loading="saveLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getTeacherSalaryList, approveSalary, rejectSalary, resendSalary, updateSalary } from '@/api/salary'

export default {
  name: 'TeacherSalary',
  setup() {
    // 响应式数据
    const loading = ref(false)
    const salaryList = ref([])
    const detailDialogVisible = ref(false)
    const currentDetail = ref(null)
    const editDialogVisible = ref(false)
    const saveLoading = ref(false)
    const editFormRef = ref(null)

    // 搜索表单
    const searchForm = reactive({
      positionName: '',
      studentName: '',
      status: ''
    })

    // 修改表单
    const editForm = reactive({
      id: null,
      positionName: '',
      studentName: '',
      hourlyRate: 0,
      totalHour: 0,
      totalSalary: 0
    })

    // 修改表单验证规则
    const editRules = {
      totalHour: [
        { required: true, message: '请输入总工时', trigger: 'blur' },
        { type: 'number', min: 0, message: '总工时不能小于0', trigger: 'blur' }
      ],
      totalSalary: [
        { required: true, message: '请输入总工资', trigger: 'blur' },
        { type: 'number', min: 0, message: '总工资不能小于0', trigger: 'blur' }
      ]
    }

    // 分页
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })

    // 获取工资列表
    const getSalaryList = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.currentPage,
          size: pagination.pageSize,
          ...searchForm
        }
        const res = await getTeacherSalaryList(params)
        let list = res.data.records || []
        // 狀態排序：未發放(2) > 待審核(0) > 已發放(1)
        list.sort((a, b) => {
          const order = {2: 0, 0: 1, 1: 2}
          return order[a.status] - order[b.status]
        })
        salaryList.value = list
        pagination.total = res.data.total || 0
      } catch (error) {
        console.error('获取工资列表失败:', error)
        ElMessage.error('获取工资列表失败')
      } finally {
        loading.value = false
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.currentPage = 1
      getSalaryList()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      pagination.currentPage = 1
      getSalaryList()
    }

    // 分页处理
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      pagination.currentPage = 1
      getSalaryList()
    }

    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      getSalaryList()
    }

    // 状态处理
    const getStatusType = (status) => {
      switch (status) {
        case 0: return 'warning'; // 待审核
        case 1: return 'success'; // 已发放
        case 2: return 'danger';  // 未发放
        default: return 'info';
      }
    }

    const getStatusText = (status) => {
      switch (status) {
        case 0: return '待审核';
        case 1: return '已发放';
        case 2: return '未发放';
        default: return '未知';
      }
    }

    // 操作处理
    const handleApprove = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要通过学生 ${row.studentName} 的工资申请吗？`,
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await approveSalary({ id: row.id })
        ElMessage.success('审核通过成功')
        getSalaryList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('审核失败:', error)
          ElMessage.error('审核失败')
        }
      }
    }

    const handleReject = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要拒绝学生 ${row.studentName} 的工资申请吗？`,
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await rejectSalary({ id: row.id })
        ElMessage.success('拒绝成功')
        getSalaryList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('拒绝失败:', error)
          ElMessage.error('拒绝失败')
        }
      }
    }

    const handlePay = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要发放学生 ${row.studentName} 的工资 ¥${row.totalSalary} 吗？`,
          '确认发放',
          {
            confirmButtonText: '确定发放',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 這裡可以調用發放工資的API
        ElMessage.success('工资发放成功')
        getSalaryList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('发放失败:', error)
          ElMessage.error('发放失败')
        }
      }
    }

    const handleViewDetail = (row) => {
      currentDetail.value = row
      detailDialogVisible.value = true
    }

    // 新增：重新发送（发放）按钮逻辑
    const handleReSubmit = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要将该工资发放提交审核吗？`,
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        await resendSalary({ id: row.id })
        ElMessage.success('已重新提交审核')
        getSalaryList()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败')
        }
      }
    }

    // 新增：修改工资信息
    const handleEdit = (row) => {
      // 复制数据到编辑表单
      Object.assign(editForm, {
        id: row.id,
        positionName: row.positionName,
        studentName: row.studentName,
        hourlyRate: row.hourlyRate,
        totalHour: row.totalHour,
        totalSalary: row.totalSalary
      })
      editDialogVisible.value = true
    }

    // 保存修改
    const handleSaveEdit = async () => {
      if (!editFormRef.value) return
      
      try {
        await editFormRef.value.validate()
        saveLoading.value = true
        
        // 这里调用修改工资的API
        await updateSalary(editForm)
        
        ElMessage.success('修改成功')
        editDialogVisible.value = false
        getSalaryList()
      } catch (error) {
        if (error !== false) { // 不是表单验证错误
          console.error('修改失败:', error)
          ElMessage.error('修改失败')
        }
      } finally {
        saveLoading.value = false
      }
    }

    // 初始化
    onMounted(() => {
      getSalaryList()
    })

    return {
      loading,
      salaryList,
      searchForm,
      pagination,
      detailDialogVisible,
      currentDetail,
      editDialogVisible,
      saveLoading,
      editFormRef,
      editForm,
      editRules,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      getStatusType,
      getStatusText,
      handleApprove,
      handleReject,
      handlePay,
      handleViewDetail,
      handleReSubmit,
      handleEdit,
      handleSaveEdit
    }
  }
}
</script>

<style scoped>
.salary-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0 0 10px 0;
  color: #303133;
}

.header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-section {
  margin-top: 20px;
  text-align: right;
}

.salary-amount {
  color: #e6a23c;
  font-weight: bold;
  font-size: 16px;
}

.detail-content {
  padding: 10px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 